package com.shadowlight.hero_story;

import com.shadowlight.hero_story.cmdHandler.HandlerFactory;
import com.shadowlight.hero_story.config.AllConfig;
import com.shadowlight.hero_story.mq.MQProducer;
import com.shadowlight.hero_story.util.RedisUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ServerMain {

    public static void main(String[] args) {
        HandlerFactory.init();
        GameMsgRecognizer.init();
        MysqlSessionFactory.init();
        RedisUtil.init();
        MQProducer.init();

        //负责处理客户端的连接，连接成功以后建立一个SocketChannel给workerGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //负责读写SocketChannel中客户端传过来的数据
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup);
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline().addLast(
                        new HttpServerCodec(),
                        new HttpObjectAggregator(65535),
                        new WebSocketServerProtocolHandler("/websocket"),
                        new GameMsgDecoder(),   //自定义消息解码器
                        new GameMsgEncoder(),   //自定义消息编码器
                        new GameMsgHandler()   //自定义消息处理器
                );
            }
        });

        try {
            ChannelFuture f = b.bind(AllConfig.GAME_SERVER_PORT).sync();

            if (f.isSuccess()) {
                log.info("服务器启动成功！");
            }

            f.channel().closeFuture().sync();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
